package vip.xiaonuo.issued.task;

import com.aliyun.oss.common.utils.DateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
public class HqDeviceHeartBeatTask implements TimerTaskRunner {

  private static final CopyOnWriteArraySet<String> currentExecuteTask = new CopyOnWriteArraySet();


  @Autowired
  private DeviceBaseService deviceBaseService;



  @Override
  public void action(String jobParams,String taskId) {
    synchronized (HqDeviceHeartBeatTask.class) {
      if (currentExecuteTask.contains(taskId)) {
        log.error("当前任务正在执行请稍后！");
        return;
      }
      log.info("心跳任务开始执行" + taskId + DateUtil.formatAlternativeIso8601Date(new Date()));
      currentExecuteTask.add(taskId);
    }
    // 心跳
    heartBeat();
    log.info("心跳任务执行结束" + taskId);
    currentExecuteTask.remove(taskId);
  }

  @Override
  @XxlJob("HQDeviceHeartBeatTask")
  public void executeXxlJob() throws InterruptedException {
    this.heartBeat();
  }

  private void heartBeat() {
    List<DeviceBase> deviceBases = deviceBaseService.list();
    for (DeviceBase deviceBase : deviceBases) {
      if (StringUtils.isBlank(deviceBase.getCabinetIp()) && StringUtils.isBlank(deviceBase.getCabinetPort())) {
        log.error("设备未设置ip和端口不进行操作!");
        continue;
      }
      Date lastOnlineTime = deviceBase.getLastOnlineTime();
      if (lastOnlineTime!=null&&DateUtils.addMinutes(new Date(), -3).after(lastOnlineTime)) {
        downDevice(deviceBase);
      }
    }
  }

  private void downDevice(DeviceBase deviceBase) {
    log.error("设备下线！" + deviceBase.getName());
    deviceBase.setDeviceState("2");
    deviceBaseService.updateById(deviceBase);
  }
}
